//
//  HMUserAccount.swift
//  WeiBo
//
//  Created by Feng on 2017/6/7.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

//保存用户信息的路径
private let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.archive")

class HMUserAccount: NSObject, NSCoding {
    //相当于令牌
    var access_token: String?
    //过期秒数
    var expires_in: Int = 0
    {
        didSet{
            //过期时间 = 当前时间 + 过期秒数
            expires_Date = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    //过期时间
    var expires_Date: Date?
    //用户id
    var uid: Int64 = 0
    //用户名
    var name: String?
    //头像大图
    var avatar_large: String?
    
    init(dict: [String: Any])
    {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
        //空实现
    }
    
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(expires_Date, forKey: "expires_Date")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeInteger(forKey: "expires_in")
        expires_Date = aDecoder.decodeObject(forKey: "expires_Date") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //读取用户资料
    class func loadUserInfoData() -> HMUserAccount? {
        let userAccount: HMUserAccount? = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? HMUserAccount
        return userAccount
    }
    
//    class func loadUserInfoData() -> HMUserAccount?
//    {
//        let userAccount: HMUserAccount = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? HMUserAccount
//        
//        return userAccount
//    }
    
    //存储用户数据
    func saveUserInfoData()
    {
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
}

